import React, { useState, useEffect } from 'react';
import { InputNumber, Button, message } from 'antd';
import { useRequest } from 'ahooks';
import nl2sqlService from '@/api/services/nl2sqlService';
import { ConnectionInfo } from '@/types/nl2sql/type';

interface QuerySettingsProps {
  selectedConnection?: ConnectionInfo | null;
}

const QuerySettings: React.FC<QuerySettingsProps> = ({ selectedConnection }) => {
  const [limitValue, setLimitValue] = useState<number>(200);

  // 获取数据库查询限制
  const { data: limitData, loading: getLoading } = useRequest(
    () => {
      if (selectedConnection?.database_id) {
        return nl2sqlService.getDatabaseLimit(selectedConnection.database_id);
      }
      return Promise.resolve({ });
    },
    {
      refreshDeps: [selectedConnection?.database_id],
      onSuccess: (data: { limit?: number }) => {
        if (typeof data?.limit === 'number') {
          setLimitValue(data.limit);
        }
      },
      onError: (error) => {
        console.error('获取查询限制失败:', error);
        // message.error('获取查询限制失败');
      },
    }
  );

  // 设置数据库查询限制
  const { run: setLimit, loading: setLoading } = useRequest(
    (limit: number) => nl2sqlService.setDatabaseLimit(selectedConnection?.database_id || '', { limit }),
    {
      manual: true,
      onSuccess: () => {
        message.success('保存成功');
      },
      onError: (error) => {
        console.error('设置查询限制失败:', error);
        message.error('保存失败');
      },
    }
  );

  // 处理保存按钮点击
  const handleSave = () => {
    if (limitValue && limitValue > 0) {
      setLimit(limitValue);
    } else {
      message.warning('请输入有效的限制数值');
    }
  };

  // 处理输入框变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = parseInt(e.target.value);
    if (!isNaN(value) && value > 0) {
      setLimitValue(value);
    }
  };

  // 当连接变化时重置状态
  useEffect(() => {
    if (selectedConnection?.database_id) {
      setLimitValue(200); // 重置为默认值
    }
  }, [selectedConnection?.database_id]);

  if (!selectedConnection) {
    return (
      <div className="flex h-full items-center justify-center">
        <div className="text-center">
          <div className="text-gray-500 mb-4">请选择一个数据库连接</div>
        </div>
      </div>
    );
  }

  return (
    <div className="flex-1 flex items-center justify-start p-4">
      <div className="w-full max-w-md">
        {/* 标题 */}
        <div className="font-semibold text-gray-800 mb-2">查询Limit</div>
        
        {/* 描述 */}
        <p className="text-gray-600 mb-6">设置默认查询结果的限制行数</p>
        
        {/* 输入框 */}
        <div className="mb-6">
          <InputNumber
            value={limitValue}
            onChange={(value) => setLimitValue(value || 0)}
            placeholder="请输入限制行数"
            className="!w-full"
            min={1}
            disabled={getLoading}
          />
        </div>
        
        {/* 保存按钮 */}
        <Button
          type="primary"
          onClick={handleSave}
          loading={setLoading}
          disabled={getLoading}
        >
          保存
        </Button>
      </div>
    </div>
  );
};

export default QuerySettings; 